#!/usr/bin/env python3
"""
AIQuant系统全面诊断脚本
检查所有可能的异步、导入和方法调用问题
"""

import asyncio
import sys
import traceback
from pathlib import Path

# 添加项目根目录到Python路径
project_root = Path(__file__).parent.parent.parent
sys.path.insert(0, str(project_root))

class SystemDiagnostics:
    """系统诊断类"""
    
    def __init__(self):
        self.results = {}
        self.total_tests = 0
        self.passed_tests = 0
        
    def log_test(self, test_name: str, success: bool, details: str = ""):
        """记录测试结果"""
        self.total_tests += 1
        if success:
            self.passed_tests += 1
            status = "✅ PASS"
        else:
            status = "❌ FAIL"
        
        self.results[test_name] = {
            "status": status,
            "success": success,
            "details": details
        }
        print(f"{status} - {test_name}")
        if details:
            print(f"    详情: {details}")
    
    async def test_database_imports(self):
        """测试数据库相关导入"""
        print("\n=== 数据库导入测试 ===")
        
        # 测试1: 检查database模块可用函数
        try:
            from aiquant.config import database
            available_functions = [attr for attr in dir(database) if not attr.startswith('_')]
            self.log_test(
                "数据库模块函数检查", 
                True, 
                f"可用函数: {available_functions}"
            )
        except Exception as e:
            self.log_test("数据库模块函数检查", False, str(e))
        
        # 测试2: 检查create_async_engine是否存在
        try:
            from aiquant.config.database import create_async_engine
            self.log_test("create_async_engine导入", True)
        except Exception as e:
            self.log_test("create_async_engine导入", False, str(e))
        
        # 测试3: 检查get_async_engine是否存在（应该失败）
        try:
            from aiquant.config.database import get_async_engine
            self.log_test("get_async_engine导入", False, "此函数不应该存在")
        except ImportError:
            self.log_test("get_async_engine导入", True, "正确：函数不存在")
        except Exception as e:
            self.log_test("get_async_engine导入", False, f"意外错误: {str(e)}")
    
    async def test_data_cache_methods(self):
        """测试DataCache类方法"""
        print("\n=== DataCache方法测试 ===")
        
        # 测试1: 正确导入DataCache
        try:
            from aiquant.data.data_cache import DataCache
            self.log_test("DataCache导入", True)
        except Exception as e:
            self.log_test("DataCache导入", False, str(e))
            return
        
        # 测试2: 检查DataCache可用方法
        try:
            cache_methods = [method for method in dir(DataCache) if not method.startswith('_')]
            self.log_test(
                "DataCache方法检查", 
                True, 
                f"可用方法: {cache_methods}"
            )
        except Exception as e:
            self.log_test("DataCache方法检查", False, str(e))
        
        # 测试3: 检查cleanup方法是否存在（应该不存在）
        try:
            cache = DataCache()
            if hasattr(cache, 'cleanup'):
                self.log_test("DataCache cleanup方法", False, "cleanup方法不应该存在")
            else:
                self.log_test("DataCache cleanup方法", True, "正确：cleanup方法不存在")
        except Exception as e:
            self.log_test("DataCache cleanup方法", False, str(e))
        
        # 测试4: 检查clear_cache方法是否存在
        try:
            cache = DataCache()
            if hasattr(cache, 'clear_cache'):
                self.log_test("DataCache clear_cache方法", True, "clear_cache方法存在")
            else:
                self.log_test("DataCache clear_cache方法", False, "clear_cache方法不存在")
        except Exception as e:
            self.log_test("DataCache clear_cache方法", False, str(e))
    
    async def test_data_adapters_issues(self):
        """测试DataAdapters中的问题"""
        print("\n=== DataAdapters问题测试 ===")
        
        # 测试1: 检查DatabaseAdapter导入问题
        try:
            # 这应该会失败，因为get_async_engine不存在
            from aiquant.data.data_adapters import DatabaseAdapter
            adapter = DatabaseAdapter()
            await adapter.initialize()
            self.log_test("DatabaseAdapter初始化", False, "应该因为get_async_engine不存在而失败")
        except Exception as e:
            if "get_async_engine" in str(e) or "cannot import name" in str(e):
                self.log_test("DatabaseAdapter初始化", True, f"正确失败: {str(e)}")
            else:
                self.log_test("DatabaseAdapter初始化", False, f"意外错误: {str(e)}")
    
    async def test_coordination_engine(self):
        """测试CoordinationEngine"""
        print("\n=== CoordinationEngine测试 ===")
        
        try:
            from aiquant.coordination import CoordinationEngine
            from aiquant.agents import AgentRegistry
            
            # 使用正确的参数创建CoordinationEngine
            registry = AgentRegistry()
            engine = CoordinationEngine(registry)
            self.log_test("CoordinationEngine创建", True)
        except Exception as e:
            self.log_test("CoordinationEngine创建", False, str(e))
    
    async def test_lifespan_basic(self):
        """测试基本lifespan功能"""
        print("\n=== 基本Lifespan测试 ===")
        
        try:
            from aiquant.main import lifespan
            from contextlib import asynccontextmanager
            
            # 创建一个模拟的FastAPI应用对象
            class MockApp:
                pass
            
            app = MockApp()
            
            # 测试lifespan上下文管理器
            async with lifespan(app):
                self.log_test("基本Lifespan功能", True, "lifespan上下文管理器正常工作")
        except Exception as e:
            self.log_test("基本Lifespan功能", False, str(e))
    
    async def search_for_similar_issues(self):
        """搜索类似的导入和方法调用问题"""
        print("\n=== 搜索类似问题 ===")
        
        import os
        import re
        
        issues_found = []
        
        # 搜索所有Python文件中的get_async_engine使用
        for root, dirs, files in os.walk("aiquant"):
            for file in files:
                if file.endswith(".py"):
                    file_path = os.path.join(root, file)
                    try:
                        with open(file_path, 'r', encoding='utf-8') as f:
                            content = f.read()
                            if 'get_async_engine' in content:
                                lines = content.split('\n')
                                for i, line in enumerate(lines, 1):
                                    if 'get_async_engine' in line:
                                        issues_found.append(f"{file_path}:{i} - {line.strip()}")
                    except Exception:
                        continue
        
        if issues_found:
            self.log_test(
                "get_async_engine使用搜索", 
                False, 
                f"发现 {len(issues_found)} 个使用: {issues_found}"
            )
        else:
            self.log_test("get_async_engine使用搜索", True, "未发现其他使用")
    
    async def run_all_tests(self):
        """运行所有测试"""
        print("🔍 开始AIQuant系统全面诊断...")
        print("=" * 60)
        
        await self.test_database_imports()
        await self.test_data_cache_methods()
        await self.test_data_adapters_issues()
        await self.test_coordination_engine()
        await self.test_lifespan_basic()
        await self.search_for_similar_issues()
        
        # 输出总结
        print("\n" + "=" * 60)
        print("📊 诊断总结")
        print("=" * 60)
        
        success_rate = (self.passed_tests / self.total_tests) * 100 if self.total_tests > 0 else 0
        print(f"总测试数: {self.total_tests}")
        print(f"通过测试: {self.passed_tests}")
        print(f"失败测试: {self.total_tests - self.passed_tests}")
        print(f"成功率: {success_rate:.1f}%")
        
        print("\n📋 详细结果:")
        for test_name, result in self.results.items():
            print(f"{result['status']} {test_name}")
            if result['details']:
                print(f"    {result['details']}")
        
        # 提供修复建议
        print("\n🔧 修复建议:")
        failed_tests = [name for name, result in self.results.items() if not result['success']]
        
        if any('get_async_engine' in name for name in failed_tests):
            print("1. 修复data_adapters.py中的get_async_engine导入错误")
        
        if any('DataCache' in name and 'cleanup' in name for name in failed_tests):
            print("2. 更新DataCache相关代码使用clear_cache而不是cleanup")
        
        if any('DatabaseAdapter' in name for name in failed_tests):
            print("3. 修复DatabaseAdapter的初始化问题")
        
        return success_rate

async def main():
    """主函数"""
    diagnostics = SystemDiagnostics()
    success_rate = await diagnostics.run_all_tests()
    
    if success_rate < 100:
        print(f"\n⚠️  发现问题，成功率: {success_rate:.1f}%")
        print("请根据上述修复建议进行修复")
        return 1
    else:
        print(f"\n✅ 所有测试通过，成功率: {success_rate:.1f}%")
        return 0

if __name__ == "__main__":
    try:
        exit_code = asyncio.run(main())
        sys.exit(exit_code)
    except KeyboardInterrupt:
        print("\n用户中断诊断")
        sys.exit(1)
    except Exception as e:
        print(f"\n诊断过程中发生错误: {e}")
        traceback.print_exc()
        sys.exit(1)